//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop

#include "Globals.h"

//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TcmForm *cmForm;
//---------------------------------------------------------------------------
__fastcall TcmForm::TcmForm(TComponent* Owner)
 : TForm(Owner)
{
}

//------------------------//
//                        //
//------------------------//
void __fastcall TcmForm::cmListDblClick(TObject *Sender)
{
  LONG ofStart[3]  = { 0x00030000, 0x000C0000, 0x00100000 };
  LONG ofFinish[3] = { 0x00030508, 0x000C0040, 0x001003A4 };
  LONG ofMin;
  LONG ofMax;

  FILE *rf;
  FILE *tf;
  BYTE *lpRam;
  LONG offset,
       lpPosi,
       size;
  LONG posi;
  long index;
  long count;
  char buf[260];

  if ( !rom ) return;

  lpRam = ( BYTE *)malloc( 0x20000 );
  if ( !lpRam ){
    ShowMessage( "Error: Out of Memory" );
    return;
  }
  //
  memcpy( lpRam, ram, 0x20000 );
  //---------------------------------
  for ( int i = 0; i < cmList->Items->Count; i++ )
  { //
    if ( cmList->Selected[ i ] )
    {
      sprintf( buf, "%s\\%08X\\", cur_dir, offset );
      mkdir( buf );
      //
      sprintf( buf, "%s\\%08X\\%08X.txt", cur_dir, offset, offset );
      tf = fopen( buf, "wt" );
      if ( !tf )
      { //
        fclose( tf );
        ShowMessage( "Error: Could not create 'DATA File'." );
        return;
      }

      //---------------------------------//
      // Select the block and decompress //
      //---------------------------------//
      ofMin = ofStart[ i ];
      ofMax = ofFinish[ i ];
      index = 0;
      // Decompress the block
      while( (ofMin + (index << 2)) < ofMax )
      { //
        posi   = (ofMin + (index << 2));
        //
        offset = posi;
        posi   = myForm->Decompress( posi );
        size   = *(WORD *)&ram[0x10000];
        //
        sprintf( buf, "%s\\%08X\\%08X.raw", cur_dir, ofMin, posi );
        rf = fopen( buf, "wb" );
        if ( rf ){
          fwrite( ram, 1, size, rf );
          fclose( rf );
        }
        //
        fprintf( tf, ".COMP %s %08X %08X\n", buf,  posi );
      }


      //
      memcpy( ram, lpRam, 0x20000 );
      _free( lpRam );
      //
//      cmForm->Close( );
      //
      if ( tf ) fclose( tf );
      ShowMessage( "All data files were decompressed!" );
    } // END IF
  }
}


